package commpackage;

import java.io.Serializable;
import java.util.*;

public class Comm implements ICommInterface {

	private HashMap threads;
	private int next_id;

	public Comm()
	{
		next_id = 0;
		threads = new HashMap();
	}

	public void connect(int id) {
		// Get the thread
		Object obj=null;
		if((obj = threads.get(new Integer(id))) != null)
		{
			ConnectionThread conn = (ConnectionThread)obj;
			conn.startSession();
		}
	}

	public void getConnections(int id)
	{
		Object obj=null;
		if((obj = threads.get(new Integer(id))) != null)
		{
			ConnectionThread conn = (ConnectionThread)obj;
			conn.getConnections();
		}
	}

	public void disconnect(int id) {

		Object obj=null;
		if((obj = threads.get(new Integer(id))) != null)
		{
			ConnectionThread conn = (ConnectionThread)obj;
			conn.endSession();
		}
	}

	public int newSession(SessionCallback cb, ConnectionType type) {

		int id = 0;
		if(next_id > 4000000)
			next_id = 0;
		else
			next_id++;
		id = next_id;

		ConnectionThread conn = new ConnectionThread(id,cb,type);
		Thread t = new Thread(conn);
		t.start();
		threads.put(new Integer(id), conn);
		return id;
	}

	public int queueMessage(int sessionid, Serializable obj) {
		int retval=-1;
		Object o=null;
		if((o = threads.get(new Integer(sessionid))) != null)
		{
			ConnectionThread conn = (ConnectionThread)o;
			retval = conn.sendObject(obj);
		}

		return retval;
	}

	public int queueRead(int sessionid)
	{
		int retval=-1;
		Object o=null;
		if((o = threads.get(new Integer(sessionid))) != null)
		{
			ConnectionThread conn = (ConnectionThread)o;
			retval = conn.receiveObject();
		}
		return retval;
	}
}
